const { API_OK } = require('../../utils/setting')
const { wxRequest, category, goodsList, bannerList } = require('../../api/goods')
const { cartList } = require('../../api/cart')
const app =  getApp()

Page({
  data: {
    loading: false,
    banner: [],
    title: '',
    currentBanner: 0,
    tabs: [],
    categoryId: 0,
    sortLabels: [
      { label: '综合', sort: false },
      { label: '销量', sort: true, status: 0 },
      { label: '新品', sort: true, status: 0 },
      { label: '价格', sort: true, status: 0 }
    ],
    activeSortIndex: 0,
    goods: [],
    cartNumber: 0
  },
  pageData: {
    page: 1,
    canLoadMore: true
  },
  async onLoad() {
    this.setData({loading: true})
    wx.showLoading({ title: '拼命加载中', mask: true })
    this.getBanner()
    await this.getTabs()
    this.getGoods()
  },
  onShow() {
    if (wx.getStorageSync('token')) {
      this.getCartNumber()
    } else {
      app.tokenReadyCallback = this.getCartNumber
    }
  },
  /**
   * 下拉刷新
   */
  async onPullDownRefresh() {
    Object.keys(wxRequest.queue).forEach(task => {
      wxRequest.queue[task].abort()
    })
    this.pageData.page = 1
    this.pageData.canLoadMore = true
    this.setData({ loading: true, goods: [], tabs: [], banner: [] })
    this.getBanner()
    await this.getTabs()
    this.getGoods()
  },
  /**
   * 加载更多数据
   */
  onReachBottom() {
    if (!this.pageData.canLoadMore) return
    this.pageData.page += 1
    this.setData({ loading: true })
    this.getGoods()
  },
  /**
   * 跳转购物车页面
   */
  goCartPage() {
    wx.switchTab({ url: '/pages/cart/cart' })
  },
  getUserInfo(e) {
    // console.log(e)
    if (e.detail.errMsg !== 'getUserInfo:ok') return
    this.setData({ userInfo: JSON.parse(e.detail.rawData) })
  },
  /**
   * 轮播切换
   */
  handleSwiperChange({ detail }) {
    // console.log(detail)
    this.setData({ currentBanner: detail.current })
  },
  /**
   * 切换商品分类
   */
  changeCategory({ detail }) {
    this.pageData.page = 1
    this.pageData.canLoadMore = true
    this.setData({ categoryId: detail.name, goods: [], loading: true })
    this.getGoods()
  },
  /**
   * 切换排序
   */
  changeActiveIndex({ detail }) {
    if (this.data.activeSortIndex === detail.index) return
    const lastIndexLabel = this.data.sortLabels[this.data.activeSortIndex]
    lastIndexLabel.sort && (lastIndexLabel.status = 0)
    this.pageData.page = 1
    this.pageData.canLoadMore = true
    this.setData({
      activeSortIndex: detail.index,
      sortLabels: this.data.sortLabels,
      goods: [],
      loading: true
    })
    this.getGoods()
  },
  /**
   * 切换升降序
   */
  changeSortStatus({ detail }) {
    const target = this.data.sortLabels[detail.index]
    target.status = target.status === 0 ? 1 : 0
    this.pageData.page = 1
    this.pageData.canLoadMore = true
    this.setData({ sortLabels: this.data.sortLabels, loading: true, goods: [] })
    this.getGoods()
  },
  /**
   * 获取轮播
   */
  async getBanner() {
    try {
      const res = await bannerList({ data: {type: 3 } })
      // console.log(res)
      if (res.code === API_OK) {
        this.setData({
          banner: res.data.lists.map(item => {
            return {
              id: item.goods_id,
              title: item.goods_name,
              image: item.image_path
            }
          })
        })
      }
    } catch(err) {
      console.warn(err)
    }
  },
  /**
   * 获取商品分类
   */
  async getTabs() {
    try {
      const res = await category({ data: {type: 3}, callback: wx.hideLoading })
      // console.log(res)
      if (res.code === API_OK) {
        const tabs = res.data.list.map(tab => ({ id: tab.category_id, label: tab.name }))
        tabs.unshift({id: 0, label: '全部商品'})
        const currentTab = tabs.filter(item => item.id === this.data.categoryId)
        const categoryId = currentTab.length ? this.data.categoryId : 0
        this.setData({ tabs, categoryId })
      }
    }
    catch(err) { console.warn(err) }
  },
  /**
   * 获取商品列表
   */
  async getGoods() {
    try {
      const res = await goodsList({
        data: {
          type: 3,
          category_id: this.data.categoryId,
          keywords: '',
          is_total: 0,
          is_sales: this.data.sortLabels[1].status,
          is_new: this.data.sortLabels[2].status,
          is_price: this.data.sortLabels[3].status,
          p: this.pageData.page
        }
      })
      wx.stopPullDownRefresh()
      if (res.code === API_OK) {
        // console.log(res)
        this.pageData.canLoadMore = res.data.list.current_page < res.data.list.last_page
        this.setData({
          loading: false,
          goods: res.data.list.data.map(goods => {
            return {
              id: goods.goods_id,
              image: (goods.image && goods.image.length) ? goods.image[0].file_path : '',
              name: goods.goods_name,
              price: goods.goods_price
            }
          })
        })
      }
    } catch (err) {
      console.warn(err)
      this.setData({ loading: false })
    }
  },
  /**
   * 获取购物车数量
   */
  async getCartNumber() {
    try {
      const res = await cartList({ callback: wx.hideLoading })
      console.log(res)
      if (res.code === API_OK) {
        this.setData({ cartNumber: res.data.order_total_num })
      }
    } catch(err) {
      console.warn(err)
    }
  }
})
